package ru.spb.osll.myfit.userchart;

import ru.spb.osll.myfit.chart.AbstractChartsBuilder;
import ru.spb.osll.myfit.common.chart.ChartCurve;
import ru.spb.osll.myfit.common.chart.ChartPoint;
import ru.spb.osll.myfit.server.chart.ChartRenderData;
import ru.spb.osll.myfit.util.parser.ILogParser;
import ru.spb.osll.myfit.util.parser.IResultSection;

import java.io.IOException;
import java.util.List;

public class ClipsWriterChartsBuilder extends AbstractChartsBuilder {

  @Override
  protected void generateCharts(List<? extends IResultSection> results) throws IOException {

    CurveCreator curveCreator = new CurveCreator();

    IResultSection sec1 = results.get(0);

    ChartRenderData renderDataBigClips = new ChartRenderData("clips_1");
    renderDataBigClips.setTitle("Write throughput clips size " + sec1.getName());

    renderDataBigClips.setHorizontalLabel("Clips");
    renderDataBigClips.setVerticalLabel("Rate, Clips/Sec");

    renderDataBigClips.getCurves().add(curveCreator.createCurve(sec1.getName(), sec1, 1, 0, 1));

    if (results.size() > 1) {

      IResultSection sec2 = results.get(1);
      ChartRenderData renderDataSmallClips = new ChartRenderData("clips_2");
      renderDataSmallClips.setTitle("Write throughput clips size " + sec2.getName());

      renderDataSmallClips.setHorizontalLabel("Clips");
      renderDataSmallClips.setVerticalLabel("Rate, Clips/Sec");

      renderDataSmallClips.getCurves().add(curveCreator.createCurve(sec2.getName(), sec2, 1, 0, 1));

      ChartRenderData renderDataBoth = new ChartRenderData("big_and_small_clips");
      renderDataBoth.setTitle("Write throughput Big and Small clips");

      renderDataBoth.setHorizontalLabel("Clips");
      renderDataBoth.setVerticalLabel("Rate, Clips/Sec");

      renderDataBoth.getCurves().add(curveCreator.createCurve(sec1.getName(), sec1, 1, 0, 1));
      renderDataBoth.getCurves().add(curveCreator.createCurve(sec2.getName(), sec2, 1, 0, 1));
      addChart(renderDataSmallClips);
      addChart(renderDataBoth);

    }
    addChart(renderDataBigClips);
  }

  @Override
  protected ILogParser getLogParser() {
    return new ClipsWriterLogParser();
  }


  private class CurveCreator {
    public CurveCreator() {

    }

    public ChartCurve createCurve(String legend, IResultSection section, int startsWithRow, int xCell, int yCell) {
      ChartCurve curve = new ChartCurve(legend);
      if (section == null || startsWithRow > section.getRows().size() || startsWithRow < 0) {
        return curve;
      }
      List<String[]> rows = section.getRows();
      int size = rows.size();
      for (int i = startsWithRow; i < size; i++) {
        String[] row = rows.get(i);
        Double x = Double.valueOf(row[xCell]);
        Double y = Double.valueOf(row[yCell]);
        curve.getPoints().add(new ChartPoint(x, y));
      }

      return curve;
    }
  }

}
